package cn.xyafu.lost.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.xyafu.lost.R;
import cn.xyafu.lost.adapter.CommentBodyAdapter;
import cn.xyafu.lost.pojo.Comment;
import cn.xyafu.lost.pojo.Lost;
import cn.xyafu.lost.utils.LostOpenHelper;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LostDetailActivity extends AppCompatActivity implements View.OnClickListener{

    private Button btn_lost_back;
    private TextView tv_detail_title;
    private TextView tv_detail_content;
    private TextView tv_detail_time;
    private EditText edt_send;
    private Button btn_send;
    private ListView lv_comment;

    private EditText edt_send_msg;
    private Button btn_send_msg;

    private String lid; // lost id

    private Lost lost;  // 当前lost
    private List<Comment> comments; // 当前comments

    private String uid; // 当前用户id

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    OkHttpClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_user_lost);
        // 获取传递过来的 lid
        Intent intent = getIntent();
        lid = intent.getStringExtra("lid");
        // 初始化组件
        initView();
        // 初始化OkHttp
        builder.connectTimeout(5, TimeUnit.SECONDS);
        builder.readTimeout(5, TimeUnit.SECONDS);
        builder.writeTimeout(5, TimeUnit.SECONDS);
        client = builder.build();
        // 初始化 uid
        uid = "7";
        LostOpenHelper openHelper = new LostOpenHelper(LostDetailActivity.this,"lostdb",null,1);
        SQLiteDatabase db = openHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from t_user", null);
        cursor.moveToFirst();	//移至第一行
        for(int i = 0; i < cursor.getCount(); i++){	//遍历每行数据
            // 获取 Uid
            uid = cursor.getString(6);
        }
        // 加载 lost comment 数据
        initData();

        btn_lost_back.setOnClickListener(this);
        btn_send.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.btn_lost_back:    // 点击返回
                finish();
                break;
            case R.id.btn_send:     // 点击发送评论
                String str = edt_send.getText().toString().trim();
                // 发送信息为空，不可发送
                if (str == "" || str == null){
                    Toast.makeText(this, "什么都不说吗？", Toast.LENGTH_SHORT).show();
                    break;
                }
                int i = sendComment(str,uid);
                if (i > 0){
                    Toast.makeText(this, "已评论", Toast.LENGTH_SHORT).show();
                    break;
                }
                Toast.makeText(this, "网络开了会儿小差", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private int sendComment(String content,String uid){
        //  发起网络请求
        // (2). 创建Request对象
        Request request = new Request.Builder().url("http://localhost/Lost_ssm/android/addComment?content="+ content +"&lid="+ lid +"&uid="+ uid).get().build();
        // (3). 创建Call对象
        Call call = client.newCall(request);
        // (4). 将请求添加到队列中
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response){
                System.out.println("请求成功");
                initComment();
            }
        });
        return 1;
    }

    private void sendStateToast(final Boolean flag){
        btn_send_msg.post(new Runnable() {
            @Override
            public void run() {
                if (flag){
                    Toast.makeText(LostDetailActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(LostDetailActivity.this, "网络异常，请稍后再试", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void showSendDialog(final String rid){

        LayoutInflater inflater = LayoutInflater.from(LostDetailActivity.this);
        View textEntryView = inflater.inflate(R.layout.dialog_sendmsg, null);
        edt_send_msg = textEntryView.findViewById(R.id.edt_send_msg);
        btn_send_msg = textEntryView.findViewById(R.id.btn_send_msg);
        AlertDialog.Builder builder = new AlertDialog.Builder(LostDetailActivity.this);
        builder.setTitle("发送消息");
        builder.setView(textEntryView);
        final Dialog dialog =  builder.show();
        WindowManager.LayoutParams wlp =dialog.getWindow().getAttributes();wlp.gravity = Gravity.TOP | Gravity.LEFT;
        wlp.x=10;
        wlp.y=240;
        dialog.getWindow().setLayout(720,580);

        btn_send_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = edt_send_msg.getText().toString().trim();
                //  发起网络请求
                // (1). 创建OkHttpCLient对象
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                builder.connectTimeout(5, TimeUnit.SECONDS);
                builder.readTimeout(5, TimeUnit.SECONDS);
                builder.writeTimeout(5, TimeUnit.SECONDS);
                OkHttpClient client = builder.build();
                // (2). 创建Request对象
                Request request = new Request.Builder().url(
                        "http://localhost/Lost_ssm/android/sendNews?rid="+ rid +"&sid="+ uid +"&nmsg="+ content).get().build();
                // (3). 创建Call对象
                Call call = client.newCall(request);
                // (4). 将请求添加到队列中
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println("请求失败");
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        System.out.println("请求成功");
                        // 将json数据转化为model数据
                        Boolean flag = Boolean.parseBoolean(response.body().string());
                        if (flag){
                            sendStateToast(true);
                            dialog.dismiss();
                        }else{
                            sendStateToast(false);
                        }
                    }
                });

            }
        });

    }

    // listView 设置点击事件
    private void setItemClickListener(ListView listView){

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = view.findViewById(R.id.comment_item_id);
                String rid = textView.getText().toString().trim();

                showSendDialog(rid);

            }
        });

    }

    private void updateView(){
        btn_lost_back.post(new Runnable() {
            @Override
            public void run() {
                // 填充 lost
                tv_detail_title.setText(lost.getLtitle());
                tv_detail_content.setText(lost.getLmsg());
                tv_detail_time.setText(lost.getLdate());
                // 填充 comment
                CommentBodyAdapter adapter = new CommentBodyAdapter(LostDetailActivity.this,comments);
                lv_comment.setAdapter(adapter);
                setItemClickListener(lv_comment);
            }
        });
    }

    private void initComment(){
        //  发起网络请求
        // (2). 创建Request对象
        Request request = new Request.Builder().url("http://localhost/Lost_ssm/android/allComments?lostid="+lid).get().build();
        // (3). 创建Call对象
        Call call = client.newCall(request);
        // (4). 将请求添加到队列中
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("请求成功");
                // 1. 将json数据转化为model数据
                String jsonString = response.body().string();
                //添加到list中
                comments = JSON.parseArray(jsonString, Comment.class);
                updateView();
            }
        });
    }

    private void initData(){
        //  发起网络请求
        // (2). 创建Request对象
        Request request = new Request.Builder().url("http://localhost/Lost_ssm/android/showLost?lid="+lid).get().build();
        // (3). 创建Call对象
        Call call = client.newCall(request);
        // (4). 将请求添加到队列中
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("请求成功");
                // 1. 将json数据转化为model数据
                String jsonString = response.body().string();
                //添加到list中
                lost = JSON.parseObject(jsonString, Lost.class);
                initComment();
            }
        });

    }

    private void initView(){
        btn_lost_back = findViewById(R.id.btn_lost_back);
        tv_detail_title = findViewById(R.id.tv_detail_title);
        tv_detail_content = findViewById(R.id.tv_detail_content);
        tv_detail_time = findViewById(R.id.tv_detail_time);
        edt_send = findViewById(R.id.edt_send);
        btn_send = findViewById(R.id.btn_send);
        lv_comment = findViewById(R.id.lv_comment);

    }

}
